package control;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.reflect.TypeToken;

import dao.DAOFactory;
import dao.Entidad;

import bean.Empleado;
import java.util.Date;
/**
 * Servlet implementation class Servlet
 */
@WebServlet("/ServletEmpleado")
public class ServletEmpleado extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public ServletEmpleado() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		
		if(request.getParameter("action")!=null){
			String action=(String)request.getParameter("action");
			List<Empleado> listEmpleado= new ArrayList<Empleado>();
					
			GsonBuilder builder = new GsonBuilder();
			builder.setDateFormat("yyyy-MM-dd");
			Gson gson = builder.create();
			
			response.setContentType("application/json");
			
			DAOFactory factory=DAOFactory.getFactoryConcrete(DAOFactory.MYSQL);
			Entidad<Empleado> empleadodao= factory.getEmpleadoDAO();
			
			if(action.equals("list")){
				try{
					
					listEmpleado = empleadodao.listAll();					
									
					JsonElement element = gson.toJsonTree(listEmpleado,new TypeToken<List<Empleado>>(){}.getType());
					JsonArray jsonArray = element.getAsJsonArray();
					String listData=jsonArray.toString();
															
					listData="{\"Result\":\"OK\",\"Records\":"+listData+"}";					
					
					response.setHeader("Cache-control", "no-cache, no-store");
			        response.setHeader("Pragma", "no-cache");
			        response.setHeader("Expires", "-1");
					response.getWriter().print(listData);
					System.out.println(listData);
					
				}catch(Exception ex){
					String error="{\"Result\":\"ERROR\",\"Message\":"+ex.getStackTrace()+"}";
					response.getWriter().print(error);
					System.out.println(error);
				}
				
			}else if(action.equals("create") || action.equals("update")){
				Empleado empleado=new Empleado();
			    
			    try{
			    	
			    	if(request.getParameter("id_pers")!=null){       
					       int id_empleado=Integer.parseInt(request.getParameter("id_pers"));
					       empleado.setId_pers(id_empleado);
				    }
				    if(request.getParameter("nomb_pers")!=null){
					       String nombre=(String)request.getParameter("nomb_pers");
					       empleado.setNomb_pers(nombre);
				    }
				    if(request.getParameter("apel_pate")!=null){
					       String apellido_paterno=(String)request.getParameter("apel_pate");
					       empleado.setApel_pate(apellido_paterno);
				    }
				    if(request.getParameter("apel_mate")!=null){
					       String apellido_materno=(String)request.getParameter("apel_mate");
					       empleado.setApel_mate(apellido_materno);
				    }
				    if(request.getParameter("dni")!=null){
				    	   int dni=Integer.parseInt((String)(request.getParameter("dni")));
				    	   empleado.setDni(dni);
					}
				    if(request.getParameter("fech_naci")!=null){
				    	System.out.println("ENTRO A LA FECHA" + request.getParameter("fech_naci"));
						SimpleDateFormat format=
								new SimpleDateFormat("yyyy-MM-dd");
						Date fechaNacimiento=new Date();
						try {
							System.out.println("ENTRO AL TRY");
							fechaNacimiento=
							format.parse(request.getParameter("fech_naci"));
							empleado.setFech_naci(fechaNacimiento);
							System.out.println("PASOO");
						} catch (ParseException e) {
							
						}	
				    }
				    if(request.getParameter("naci")!=null){
				    	   String nacionalidad=((String)request.getParameter("naci"));
				    	   empleado.setNaci(nacionalidad);
					}
				    if(request.getParameter("dire")!=null){
					       String direccion=((String)request.getParameter("dire"));
					       empleado.setDire(direccion);
				    }
				    if(request.getParameter("celu")!=null){
					       int celular=Integer.parseInt((String)request.getParameter("celu"));
					       empleado.setCelu(celular);
					}
				  
				    if(request.getParameter("tele")!=null){
				    	 int telefono=Integer.parseInt((String)(request.getParameter("tele")));
				    	   empleado.setTele(telefono);
					}
				    if(request.getParameter("id_pais")!=null){
			    		int id_pais=Integer.parseInt((String)request.getParameter("id_pais"));
				       empleado.setId_pais(id_pais);
				    }
				    if(request.getParameter("id_depa")!=null){
			    		int id_departamento=Integer.parseInt((String)request.getParameter("id_depa"));
				       empleado.setId_depa(id_departamento);
				    }
				    if(request.getParameter("id_provincia")!=null){
			    		int id_provincia=Integer.parseInt((String)request.getParameter("id_prov"));
				       empleado.setId_prov(id_provincia);
				    }
				    if(request.getParameter("id_distrito")!=null){
			    		int id_distrito=Integer.parseInt((String)request.getParameter("id_dist"));
				       empleado.setId_dist(id_distrito);
				    }
			    	
			    if(request.getParameter("rol")!=null){
				   String rol = ((String)request.getParameter("rol"));
				   empleado.setRol(rol);
			   	}  
			    if(request.getParameter("area")!=null){
			    	   String area=((String)request.getParameter("area"));
			    	   empleado.setArea(area);
				}
			    if(request.getParameter("suel")!=null){
			    	double sueldo=Double.parseDouble((String)request.getParameter("sueldo"));
			    	empleado.setSuel(sueldo);
				}
			    }catch(Exception e){
			    	System.out.print("Error al capturar datos " + e.getMessage());
			    }
			    
			    try{           
			     if(action.equals("create")){//Create new record
			      empleadodao.insert(empleado);     
			      listEmpleado.add(empleado); 
			      //Convert Java Object to Json    
			      String json=gson.toJson(empleado);     
			      //Return Json in the format required by jTable plugin
			      String listData="{\"Result\":\"OK\",\"Record\":"+json+"}";           
			      response.getWriter().print(listData);
			     }else if(action.equals("update")){//Update existing record
			    	 empleadodao.update(empleado);
			      String listData="{\"Result\":\"OK\"}";         
			      response.getWriter().print(listData);
			     }
			    }catch(Exception ex){
			      String error="{\"Result\":\"ERROR\",\"Message\":"+ex.getStackTrace().toString()+"}";
			      response.getWriter().print(error);
			    }
			   }else if(action.equals("delete")){//Delete record
			    try{
			     if(request.getParameter("id_pers")!=null){
			     Empleado empleado = new Empleado();
			     	try{
			     		if(request.getParameter("id_pers")!=null){       
			     		int id_empleado=Integer.parseInt(request.getParameter("id_pers"));
			     		empleado.setId_pers(id_empleado);
						}
					}catch(Exception e){
					    System.out.print("Error al capturar datos " + e.getMessage());
					}
			     	empleadodao.delete(empleado);
			      String listData="{\"Result\":\"OK\"}";        
			      response.getWriter().print(listData);
			     }
			    }catch(Exception ex){
			    String error="{\"Result\":\"ERROR\",\"Message\":"+ex.getStackTrace().toString()+"}";
			    response.getWriter().print(error);
			   }    
			  }
			
		}
		
		
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		
		doGet(request, response);
	}

}
